Skip to content

dev: add warning when context is undefined#2466

Closed
Tommypop2 wants to merge 2 commits into
solidjs:mainfrom
Tommypop2:main
Closed

dev: add warning when context is undefined#2466
Tommypop2 wants to merge 2 commits into
solidjs:mainfrom
Tommypop2:main

Conversation

@Tommypop2
Copy link
Copy Markdown

@Tommypop2 Tommypop2 commented Apr 8, 2025

Summary

Using useContext outside of a provider can cause unforeseen and cryptic errors. This PR adds a warning (in dev) when the result of useContext is falsy.

See https://discord.com/channels/722131463138705510/1358899310116213008

Typescript does protect against using an undefined context somewhat, but I thought a warning could be nice, especially for new users.

How did you test this change?

Created a project and consumed a context without being in its provider:
image

Warning is printed to the console.

After the project has been built, the warning is not logged.

@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented Apr 8, 2025

⚠️ No Changeset found

Latest commit: bc6c19b

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@Tommypop2 Tommypop2 changed the title dev: add warning when context is null dev: add warning when context is undefined Apr 8, 2025
@ryansolid
Copy link
Copy Markdown
Member

Thanks for the PR. I’m going to close this as stale for Solid 2.

The underlying issue is real: reading a default-less context outside its Provider can lead to confusing errors later. In Solid 2, though, default-less contexts now throw immediately when read without a Provider, and useContext(createContext<T>()) is typed as T, so this is handled more directly.

I also don’t think this exact warning is safe to add. Context values can legitimately be falsy — false, 0, "", or even null depending on the context type — so warning based on a falsy result would produce false positives.

For the 1.x line, I think the better fix is a type-level one: distinguish default-less contexts so providers don’t accidentally accept undefined unless the context type explicitly includes it. That addresses the common mistake without warning on valid context values. As outlined as my response to #1958.

@ryansolid ryansolid closed this May 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants